package cn.usts.edu.lesson03;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;

// 鼠标监听事件
public class TestMouseListener {
    public static void main(String[] args) {
        new MouseListenerFrame("鼠标监听");
    }

}

class MouseListenerFrame extends Frame{
    ArrayList points;// 设置一个集合用来存储目鼠标点击的位置

    public MouseListenerFrame(String title){
        super(title);
        setBounds(100,100,400,400);
        setVisible(true);

        // 记录下的点位
        points = new ArrayList<>();

        // 鼠标监听
        this.addMouseListener(new MyMouseListener());
        // 窗口监听
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    // 重写画笔方法
    @Override
    public void paint(Graphics g) {
        // 画画,监听鼠标事件
        Iterator iterator = points.iterator(); // 转可迭代对象
        while (iterator.hasNext()){
            Point point = (Point)iterator.next();
            g.setColor(Color.orange); // 设置颜色
            g.fillOval(point.x,point.y,10,10);// 获取点的位置,每个位置画出一个10*10的实心圆
        }

    }

    // 添加一个点到界面上
    public void addPoint(Point point){
        points.add(point);
    }

    private class MyMouseListener extends MouseAdapter{
        @Override
        public void mousePressed(MouseEvent e) {
            // 获取调用鼠标资源的对象
             MouseListenerFrame mouseListenerFrame = (MouseListenerFrame) e.getSource();
             // 添加点的位置
             mouseListenerFrame.addPoint(new Point(e.getX(),e.getY()));
             // 鼠标每点击一次就刷新一次
             mouseListenerFrame.repaint();
        }
    }
}